package com.lx.controller;

import com.lx.custom.AjaxException;
import com.lx.custom.WebException;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 增强器
 *
 * @author 段誉
 * @create 2019-03-14 20:43
 */
@Slf4j
@ControllerAdvice
public class MyControllerAdvice {
  /**
   * 应用到所有RequestMaping注解方法，在其执行之前初始化数据绑定器
   * @param binder
   */
  @InitBinder
  public void initBinder(WebDataBinder binder) {
  }

  /**
   * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
   * @param model
   */
  @ModelAttribute
  public void addAttributes(Model model) {
    model.addAttribute("author", "Jacob");
  }

  /**
   * 全局异常拦截，value设置拦截exception异常
   * @param ex
   *
   * @return
   */
  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public Map errorHandler(Exception ex) {
    Map map = new HashMap();
    map.put("code", 100);
    map.put("msg", ex.getMessage());
    return map;
  }

  /**
   * 自定义异常拦截，拦截AjaxException异常返回json数据
   * @param ex
   * @return
   */
  @ExceptionHandler(value = AjaxException.class)
  @ResponseBody
  public Map ajaxErrorHandler(AjaxException ex) {
    Map map = new HashMap();
    map.put("code", ex.getCode());
    map.put("msg", ex.getMsg());
    return map;
  }

  @ExceptionHandler(value = WebException.class)
  public ModelAndView webErrorHandler(WebException ex) {
    ModelAndView modelAndView = new ModelAndView();
    //设置跳转的页面
    modelAndView.setViewName("error");
    //设置页面参数
    modelAndView.addObject("code", ex.getCode());
    modelAndView.addObject("msg", ex.getMsg());
    return modelAndView;
  }
}
